import 'dart:io';

import 'package:collection/collection.dart';
import 'package:path/path.dart';

Future<void> generateRustMod(
  Uri dir, {
  List<String> extraLines = const [],
}) async {
  final files = Directory(dir.toFilePath())
      .listSync()
      .map((entity) {
        if (entity is File) {
          final name = basenameWithoutExtension(entity.path);
          if (name == 'mod') return null;
          return name;
        }
        if (entity is Directory) {
          return basename(entity.path);
        }
        return null;
      })
      .whereNotNull()
      .toList()
      .sorted();

  const kPrefixes = {
    'conditionally_compiled_module': '#[cfg(target_os = "non_existent_os")]',
    'deliberately_ignored_module': '/// flutter_rust_bridge:ignore\n',
  };

  final lines = [
    '// AUTO-GENERATED BY frb_internal, PLEASE DO NOT EDIT',
    for (final file in files) '${kPrefixes[file] ?? ""}pub mod $file;',
    '',
    ...extraLines,
  ];

  File(dir.resolve('mod.rs').toFilePath()).writeAsStringSync(lines.join('\n'));
}
